<?php

namespace App\Jobs;

use App\Models\GrGood;
use App\Models\GrOrder;
use App\Models\GrOrderGoods;
use App\service\RabbitmqServer;
use Carbon\Carbon;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class Queue implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public $goods_data;
    public $order_data;
    public $end_time;
    public $seckill_id;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($goods_data, $order_data, $end_time, $seckill_id)
    {
        $this->goods_data = $goods_data;//商品数据
        $this->order_data = $order_data;//订单数据
        $this->end_time = $end_time;//结束时间
        $this->seckill_id = $seckill_id;//秒杀活动id
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
//        订单编号
        try {
            //rabbitmq队列存储
            DB::beginTransaction();
            $time = Carbon::now()->endOfDay()->toArray();
            $day_end = $time['timestamp'] - time();//今天结束时间
            $goods_id = $this->goods_data['goods_id'];
            $order_data = GrOrder::create($this->order_data);//添加订单数据
            $Rabbit = new RabbitmqServer("x-delayed-message");//调用延时队列
//            //第一个参数发送的消息，第二个参数延迟多少秒
            $Rabbit->sendDelay($order_data->id, 10);//先入列30分钟后检测订单支付状态
            $order = $order_data->toArray();
            $this->goods_data['order_id'] = $order['id'];
            GrOrderGoods::create($this->goods_data);//添加订单商品数据
            $total = GrGood::where('goods_id', $goods_id)->pluck('stock_total');//查询原有库存数量
            $number = Redis::get('purchase_number' . $order_data['user_id'] . '_' . $this->seckill_id);//存储参与次数
            if ($number == null) {//判断今天是否参与过活动
                Redis::setex('purchase_number' . $order_data['user_id'] . '_' . $this->seckill_id, $day_end, 1);
            }//参与过就原来数据+1没参与过添加数据
            Redis::setex('purchase_number' . $order_data['user_id'] . '_' . $this->seckill_id, $day_end, $number + 1);
            $new_total = $total[0] - $this->goods_data['goods_number'];//直接修改库存或也可以在活动结束库存归还
            GrGood::where('goods_id', $goods_id)->update(['stock_total' => $new_total]);
            Redis::rpop('number' . $this->seckill_id);
        } catch (\Exception $exception) {
            DB::rollBack();
            echo '订单生成失败';
        }
        DB::commit();
        echo '订单生成成功';
    }
}
